package cn.changeforyou.analyzer.xmlparse.mybatis.model;

import cn.changeforyou.analyzer.CombineElement;
import cn.changeforyou.analyzer.combine.orm.compare.ComparedStruct;
import cn.changeforyou.analyzer.naming.NamingStrategy;
import java.util.Collections;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.dom4j.tree.DefaultElement;

import java.util.List;

/**
 * mybatis xml文档的sql标签
 *
 * @author zhyu
 */
@Data
public class SqlLabel extends MybatisXmlLabel<DefaultElement> {
	
	private List<SqlField> sqlFields;
	private String sql;
	
	@Override
	public List<String> getComparedStruct() {
		List<String> list = sqlFields.stream().map(x -> x.getName(getNamingStrategy())).collect(Collectors.toList());
		Collections.sort(list);
		return list;
	}
	
	@Override
	public NamingStrategy getNamingStrategy() {
		switch (getId()) {
			case Base_Column_List:
				return NamingStrategy.camelCase;
			case Alias_Column_List:
				return NamingStrategy.sqlFieldWithAliasNaming;
		}
		throw new IllegalArgumentException("参数异常");
	}
	
	@Override
	public String getStructName() {
		return getTableName();
	}
	
	@Getter
	@Setter
	public static class SqlField implements CombineElement {
		
		private String columnName;
		private String aliasName;
		private SqlLabel sqlLabel;
		
		public SqlField(SqlLabel sqlLabel) {
			this.sqlLabel = sqlLabel;
		}
		
		@Override
		public String getName() {
			return columnName;
		}
		
		@Override
		public ComparedStruct getParentStruct() {
			return sqlLabel;
		}
		
		@Override
		public String toString() {
			return "SqlField{" +
				       "columnName='" + columnName + '\'' +
				       ", aliasName='" + aliasName + '\'' +
				       ", sqlLabel=@" + sqlLabel.hashCode() +
				       '}';
		}
	}
}
